package com.test.dababy.dababy_00_analytics.DababyUtil

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.adjust.sdk.*
import com.test.dababy.dababybean.PamdababyAdababydjustInst
import com.test.dababy.dababy_00_analytics.dababyevent.DababyIAnalyticsEvent
import com.test.dababy.dababy_00_analytics.dababyhttp.DababyHttpHelper
import com.test.dababy.dababy_00_utils.DababyConfigs
import com.test.dababy.dababy_00_utils.DababyConfigs.AJ_EVE_dababyNT_APPLY
import com.test.dababy.dababy_00_utils.DababyConfigs.AJ_EVENT_RE_dababyGISTER
import com.test.dababy.dababy_00_utils.DababyConfigs.AJ_TO_dababyKEN
import com.test.dababy.dababy_00_path.Paths_dababy
import com.test.dababy.dababy_00_utils.DababyUtil

object DababyAdjustUtil {

    /** 归因信息 */
    var adjsutAttribution_dababy: PamdababyAdababydjustInst? = null

    /**
     * 初始化Adjust模块
     * 按配置需要来初始化
     *
     * @param context Application
     */
    fun init_dababy(context: Application) {
        if (AJ_TO_dababyKEN.isBlank()) throw Exception("Error: Adjust Token must no be null!")
        if (AJ_EVENT_RE_dababyGISTER.isBlank()) throw Exception("Error: Adjust Register code must no be null!")
        if (AJ_EVE_dababyNT_APPLY.isBlank()) throw Exception("Error: Adjust Apply code must no be null!")

        val config = AdjustConfig(context, AJ_TO_dababyKEN, DababyConfigs.Enviro_dababynment)

        // 日志级别
        config.setLogLevel(LogLevel.INFO)

        // 监听归因回调
        config.setOnAttributionChangedListener { covertAndSaveAttributtion_dababy(it) }

        // 初始化
        Adjust.onCreate(config)

        // 配置页面监听
        registerAdjustActivityLifecycle_dababy(context)

        // 获取当前归因信息
        // 每次初始化都需要重新获取，
        // 因为 setOnAttributionChangedListener 不一定回调多次
        val attribution = Adjust.getAttribution()
        covertAndSaveAttributtion_dababy(attribution)
    }

    /**
     * 过滤Adjsut归因信息，
     * 并上传
     *
     * @param attribution AdjustAttribution
     */
    private fun covertAndSaveAttributtion_dababy(attribution: AdjustAttribution?) {
        attribution?.let { result ->
            //组装
            adjsutAttribution_dababy = PamdababyAdababydjustInst()

            //adjust 归因参数
            adjsutAttribution_dababy?.let { params ->
                params.adid = result.adid.orEmpty()
                params.network = result.network.orEmpty()
                params.adgroup = result.adgroup.orEmpty()
                params.creative = result.creative.orEmpty()
                params.costType = result.costType.orEmpty()
                params.campaign = result.campaign.orEmpty()
                params.clickLabel = result.clickLabel.orEmpty()
                params.trackerName = result.trackerName.orEmpty()
                params.trackerToken = result.trackerToken.orEmpty()
                params.costCurrency = result.costCurrency.orEmpty()
                params.fbInstallReferrer = result.fbInstallReferrer.orEmpty()
                result.costAmount?.let { costAmount ->
                    params.costAmount = costAmount.toString()
                }

                //上报
                println("=====adjust attribution:")
                println(result)

                val pathList = mutableListOf(
                    DababyUtil.getCommonPath_dababy()
                )
                saveInstallInfo_dababy(pathList)
            }
        }
    }

    /**
     * 配置Adjust 页面监听
     * 如果其它模块有注册callback
     * 注意调用顺序或合并adjus
     *
     * @param context Application
     */
    fun registerAdjustActivityLifecycle_dababy(context: Application) {
        context.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(p0: Activity, p1: Bundle?) {
            }

            override fun onActivityStarted(p0: Activity) {
            }

            override fun onActivityResumed(p0: Activity) {
                Adjust.onResume()
            }

            override fun onActivityPaused(p0: Activity) {
                Adjust.onPause()
            }

            override fun onActivityStopped(p0: Activity) {
            }

            override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
            }

            override fun onActivityDestroyed(p0: Activity) {
            }
        })
    }

    /**
     * 打点
     *
     * @param event 事件名
     */
    fun addEvent_dababy(event: DababyIAnalyticsEvent) {
        try {
            when (event) {
                DababyIAnalyticsEvent.AT_REGISTER -> {
                    Adjust.trackEvent(AdjustEvent(AJ_EVENT_RE_dababyGISTER))
                }
                DababyIAnalyticsEvent.AT_LOAN_APPLY -> {
                    Adjust.trackEvent(AdjustEvent(AJ_EVE_dababyNT_APPLY))
                }
                else -> {}
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 保存Appsflyer 安装信息
     */
    fun saveInstallInfo_dababy(targetUrlList: List<String>) {
        adjsutAttribution_dababy?.let { data ->
            try {
               val body = data.toEncryptParams(Paths_dababy.PATH_ADJUST_INSTALL)
//                val body = Gson().toJson(adjsutAttribution).trim()
                println("====== $targetUrlList")

                //传多国时，里触发多次
                val apiPath = DababyUtil.getCommonPath_dababy()
                targetUrlList.forEach { host ->
                    val pathFormat =
                        if (host.endsWith(apiPath)) host else (host + apiPath)
                    DababyHttpHelper.postData_dababy(pathFormat, body)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}